package main;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

import javax.microedition.lcdui.game.Sprite;
import javax.microedition.lcdui.Image;

public class ThrewObject {

    public static final double GRAVITY = 2.0;
    private int _weight;
    private double _throwAngle;
    private double _thrownPower;
    private double _t = 0;
    private boolean _isRuning;

    public double getTime() {
        return _t;
    }

    public ThrewObject() {
        _isRuning = true;
    }

    public void setThrowParameter(double throwAngle, double thrownPower) {
        _throwAngle = throwAngle;
        _thrownPower = thrownPower;
        _t = 0;
    }

    public void activate() {
        _isRuning = true;
    }

    public void deactivate() {
        _isRuning = false;
    }

    public void reset() {
        _t = 0;
        _throwAngle = 0;
        _thrownPower = 0;
    }

    public void run(Point point) {
        if (_isRuning) {
            double dt = 1;
            //if (_t > 0) {
                double x = _thrownPower * Math.cos(_throwAngle) * dt;
                double y = _thrownPower * Math.sin(_throwAngle) * dt - GRAVITY * dt * (2 * _t + dt) / 2;
                point.move((int) x, -(int) y);
            //}
            _t += dt;

        }
    }

    public static boolean moveSpriteTo(Sprite sp, Sprite map, int xNew, int yNew,boolean checkCollides) {

        boolean isCollides = false;

        Sprite pos = new Sprite(Image.createImage(1, 1));
        pos.defineReferencePixel(sp.getX() - sp.getRefPixelX(), sp.getY() - sp.getRefPixelY());



        float x = sp.getRefPixelX();
        float y = sp.getRefPixelY();
        int dx = xNew - (int) x;
        int dy = yNew - (int) y;
        if (dx == 0 && dy == 0) {
            return false;
        }
        float m = (float)dx/dy;
        float incX;
        float incY;
        int step = 0;
        /*dx = Math.abs(dx);
        dy = Math.abs(dy); */       

        if (Math.abs(m) > 1) {
            if (dx > 0) {
                incX = 1;
            } else {
                incX = -1;
            }
            incY = incX  / m;
            step = Math.abs(dx);
        } else {
            if (dy > 0) {
                incY = 1;
            } else {
                incY = -1;
            }
            incX = incY * m;
            step = Math.abs(dy);
        }
        pos.setPosition((int) x, (int) y);
        //boolean isOnGround = pos.collidesWith(map, true);
        for (int i = 0; i < step; i++) {
            pos.setPosition((int) x, (int) y);
            if (checkCollides && pos.collidesWith(map, true)) {
                    isCollides = true;
                    break;
            }
            x = x + incX;
            y = y + incY;
        }
        sp.setPosition(pos.getRefPixelX(), pos.getRefPixelY());
        return isCollides;

    }
}
